package com.lilanz.microservice.express.utils.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * @ Description：全局异常处理，把错误的信息返回给前端
 */
@RestControllerAdvice
public class ExceptionConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 最大的异常处理,所有的Exception的异常都在这里,并返回
    @ExceptionHandler(Exception.class)
    public Map<String, Object> Exception(HttpServletRequest request, Exception e) {
        String errorMessage = "错误信息:" + e.getMessage() + " 错误的接口: " + request.getRequestURL();
        logger.error(errorMessage);
        // 返回给前端错误的信息
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("message", "系统错误");
        map.put("errorMessage", e.getMessage());
        // 用来知道哪个接口出现异常,为以后编写
        map.put("url", request.getRequestURL());
        return map;
    }

    // 自定义异常处理
    @ExceptionHandler(MyException.class)
    public Map<String, Object> myException(HttpServletRequest request, MyException e) {
        String errorMessage = "错误信息:" + e.getMessage() + " 错误的接口: " + request.getRequestURL();
        logger.error(errorMessage);
        // 返回给前端错误的信息
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("message", e.getMessage());
        // 用来知道哪个接口出现异常,为以后编写
        map.put("url", request.getRequestURL());
        return map;
    }
}
